package com.example.cardgame

import android.annotation.SuppressLint
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import cn.edu.sicnu.cardgame.CardMatchingGame

class GameActivity : ComponentActivity(), View.OnClickListener {
    // 定义一个CardMatchingGame对象
    private lateinit var game: CardMatchingGame
    //定义卡片列表
    private var cardButtons = mutableListOf<Button>()
    //定义最高分
    private var bestscore: Int = 0
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_game)

        val gridLayout: GridLayout = findViewById(R.id.gridLayout)
        val reset = findViewById<Button>(R.id.reset)
        val exit = findViewById<Button>(R.id.exit)

        //遍历GridLayout中的所有Button并添加到cardButtons列表中
        for(v in gridLayout.children) {
            if(v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        //初始化CardMatchingGame对象
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        //重置按钮点击事件
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        //退出按钮点击事件
        exit.setOnClickListener {
            if(game.score > bestscore) {
                intent.putExtra("bestscore", game.score)
                setResult(RESULT_OK, intent)
            }
            finish()
        }
    }
    //更新UI
    @SuppressLint("DefaultLocale")
    fun updateUI() {
        for(button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if(card.isChosen) {
                button.text = card.toString()  //显示已选中的卡片花色和数字
                button.setBackgroundColor(Color.White.toArgb())
            } else {
                button.text = ""  //清空未选中的卡片
                button.setBackgroundResource(R.drawable.cardbackground)
            }
        }
        //显示分数
        val score = findViewById<TextView>(R.id.score)
        score.text = String.format("%s%s", getString(R.string.score), game.score)
    }

    //按钮点击事件
    override fun onClick(v: View?) {
        if(v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)  //选择卡片
            updateUI()  //更新UI
        }
    }
}






